package com.hx.vending.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * example byte[] bytes = ByteUtils.get().add(0x41).add(07).add(11).add("15288930000").add(0x45).toArray();
 * Created by zhrt on 2017/8/31.
 */

public class ByteUtils {
    static ByteUtils mByteUtils = new ByteUtils();
    static ByteArrayOutputStream baos = new ByteArrayOutputStream();

    private ByteUtils() {
    	
    }

    public static ByteUtils get() {
        baos.reset();
        return mByteUtils;
    }

    public ByteUtils add(byte[] bytes) {
        try {
            baos.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mByteUtils;
    }

    public ByteUtils add(byte by) {
        try {
            baos.write(new byte[]{by});
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mByteUtils;
    }

    public ByteUtils add(String str) {
        try {
            baos.write(str.getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mByteUtils;
    }
    public ByteUtils addHex(String deviceID) {
        try {
            for (int i = 0; i < deviceID.length(); i+=2) {
                int i1 = Integer.parseInt(deviceID.substring(i,i+2), 16);
                baos.write(i1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mByteUtils;
    }


    public ByteUtils add(int i) {
        baos.write(i);
        return mByteUtils;
    }

    public byte[] toArray() {
        //Log.i("..ByteArray", ": " + toHexString(baos.toByteArray()));
        return baos.toByteArray();
    }

    public static String toHexString(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder("[0x");
        if (bytes == null || bytes.length <= 0) return "";
        for (int i = 0; i < bytes.length; i++) {
            String hv = Integer.toHexString(bytes[i] & 0xFF);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
            if (i == bytes.length - 1) {
                stringBuilder.append("]");
            } else if (i == 1000) {
                i = bytes.length - 50;
                stringBuilder.append("......");
            } else if (i % 10 == 9) {
                stringBuilder.append(",  ");
            } else if (i < bytes.length - 1) {
                stringBuilder.append(", ");
            }
        }
        return stringBuilder.toString();
    }

}
